package com.zc.webnews.ui;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.zc.webnews.R;
import com.zc.webnews.adapter.MyNewsFragmentAdapter;
import com.zc.webnews.adapter.TypeGridViewAdapter;
import com.zc.webnews.application.Constant;
import com.zc.webnews.application.MyApplication;
import com.zc.webnews.bean.NewsDetailsBean;
import com.zc.webnews.fragment.BaseNews;
import com.zc.webnews.utils.HttpUrlUtils;
import com.zc.webnews.utils.MyBmobUtils;
import com.zc.webnews.utils.SharepreferencesUtilSystemSettings;
import com.zc.webnews.utils.XmlParseUtils;
import com.zc.webnews.view.indicator.PageIndicator;
import com.zc.webnews.view.slidingmenu.SlidingMenu;


import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class NewsActivity extends BaseFragmentActivity implements View.OnClickListener {

    private MyBmobUtils myBmobUtils;
    private ViewPager viewPager;
    private PageIndicator mIndicator;
    public List<BaseNews> list = new ArrayList<BaseNews>();
    private SlidingMenu slidingMenu;
    private ImageView add_newsChannel, menu,touXiang;
    private MyNewsFragmentAdapter adapter;
    //文章的收藏集合
    public List<NewsDetailsBean> collectionList = new ArrayList<>();
    //侧滑菜单中频道和新闻类别的选择控件
    private GridView typeGridView;
    private TypeGridViewAdapter typeGridViewAdapter;
    //选择频道中，前一个选择的频道与新闻类别
    public static TextView tv_preTypeSelected;
    private static int preTypeSelected = 0;
    private HttpUrlUtils httpUrlUtils;
    public static List<String> list_title = new ArrayList<>();
    public List<String> title = new ArrayList<>();
    public static List<String> list_url = new ArrayList<>();
    private ListView setListView;
    private TextView name;
    private String[] list_seting = {"我的收藏", "注销登录"};
    private int screen_width;
    private MyApplication myApplication;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0){
                initData();
            }else if (msg.what == 200){
                if (MyApplication.mAccount.getImage()==null){
                    menu.setImageResource(R.mipmap.touxiang);
                    touXiang.setImageResource(R.mipmap.touxiang);
                }else {
                    String url = MyApplication.mAccount.getImage().getFileUrl();
                    Picasso.with(NewsActivity.this).load(url).into(menu);
                    Picasso.with(NewsActivity.this).load(url).into(touXiang);
                }
            }
        }
    };
    /* 指示器切换监听 */
    private ViewPager.OnPageChangeListener IndicatorOnPageChangedListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            Constant.pos = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };
    /* 页卡切换监听 */
    private ViewPager.OnPageChangeListener viewPagerOnPageChangedListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            Constant.pos = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getScreenWH();
        setContentView(R.layout.activity_news);
        initView();
        initListener();
        if (XmlParseUtils.isFirst) {
            getNewsData();
            XmlParseUtils.isFirst = false;
        } else {
            initData();
        }
        collectionList.clear();
    }

    /**
     * 获取新闻信息Xml
     */
    private void getNewsData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                XmlParseUtils xmlParseUtils = new XmlParseUtils();
                httpUrlUtils = HttpUrlUtils.getInstance();
                InputStream input = httpUrlUtils.getInputStream(Constant.XMLPATH);
                xmlParseUtils.pullParseChannelXml(input);
                handler.sendEmptyMessage(0);
            }
        }).start();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //设置博客新闻频道
        setChannelTitle(1);
        //设置新闻类别
        title.clear();
        title.addAll(XmlParseUtils.list_channelAndNews.get(1).getTitle());
        typeGridViewAdapter = new TypeGridViewAdapter(this, title);
        typeGridView.setAdapter(typeGridViewAdapter);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.setting_items, list_seting);
        setListView.setAdapter(adapter);
        myApplication = (MyApplication) getApplication();
        name.setText(MyApplication.mAccount.getAccount());
        myBmobUtils = new MyBmobUtils();
        myBmobUtils.context = NewsActivity.this;
        myBmobUtils.queryUserHead();
    }

    /**
     * 获取手机屏幕宽高
     */
    private void getScreenWH() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screen_width = metrics.widthPixels;
    }

    /**
     * 侧滑菜单的设置
     */
    private void initSlidingMenu() {
        //创建SlidingMenu对象
        slidingMenu = new SlidingMenu(this);
        //设置不用触摸屏幕模式打开侧滑菜单
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        //设置侧滑菜单模式
        slidingMenu.setMode(SlidingMenu.LEFT_RIGHT);
        //设置侧滑菜单的显示宽度
        slidingMenu.setBehindOffset(screen_width / 4);
        //将侧滑菜单加入到当前的界面中
        slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        //设置侧滑菜单的布局样式
        slidingMenu.setMenu(R.layout.sliding_left);
        slidingMenu.setSecondaryMenu(R.layout.sliding_right);

        slidingMenu.setOnCloseListener(new SlidingMenu.OnCloseListener() {
            @Override
            public void onClose() {
                add_newsChannel.startAnimation(StartAnimation(225f, 0f));
            }
        });
    }

    /**
     * 侧滑菜单动画
     *
     * @param x
     * @param y
     * @return
     */
    private Animation StartAnimation(float x, float y) {
        RotateAnimation animation = new RotateAnimation(x, y,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setFillAfter(true);
        animation.setDuration(300);
        return animation;
    }

    private Animation StartAlphaAnimation(float x, float y) {
        AlphaAnimation animation = new AlphaAnimation(x, y);
        animation.setFillAfter(true);
        animation.setDuration(300);
        return animation;
    }

    /**
     * 设置监听事件
     */
    private void initListener() {
        viewPager.setOnPageChangeListener(viewPagerOnPageChangedListener);
        mIndicator.setOnPageChangeListener(IndicatorOnPageChangedListener);
        add_newsChannel.setOnClickListener(this);
        menu.setOnClickListener(this);
        touXiang.setOnClickListener(this);
        typeGridView.setOnItemClickListener(typeGridViewListener);
        setListView.setOnItemClickListener(setListener);
    }

    private AdapterView.OnItemClickListener setListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
                case 0:
                    startActivity(new Intent(NewsActivity.this,ShowCollectionActivity.class));
                    break;
                case 1:
                    AlertDialog.Builder builder = new AlertDialog.Builder(NewsActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("是否确定退出？");
                    builder.setNegativeButton("否", null);
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            myApplication.isLogin = true;
                            SharepreferencesUtilSystemSettings.putValue(NewsActivity.this, Constant.ISLOGIN, myApplication.isLogin);
                            startActivity(new Intent(NewsActivity.this, LoginActivity.class));
                            finish();
                        }
                    });
                    builder.show();
                    break;
            }
        }
    };

    /**
     * 初始化控件
     */
    private void initView() {
        viewPager = (ViewPager) findViewById(R.id.pvr_user_pager);
        mIndicator = (PageIndicator) findViewById(R.id.pvr_user_indicator);
        add_newsChannel = (ImageView) findViewById(R.id.news_add);
        menu = (ImageView) findViewById(R.id.news_touxiang);
        initSlidingMenu();
        touXiang = (ImageView) findViewById(R.id.sliding_left_touxiang);
        setListView = (ListView) findViewById(R.id.sliding_left_listView);
        typeGridView = (GridView) findViewById(R.id.sliding_right_type_GridView);
        name = (TextView) findViewById(R.id.sliding_left_name);
        XmlParseUtils.isPreSelectFirst = true;
        XmlParseUtils.isPreTypeSelectFirst = true;
        setOrChangeTranslucentColor(findViewById(R.id.news_rl), getResources().getColor(R.color.dip_red));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.news_touxiang:
                if (!slidingMenu.isMenuShowing()) {
                    myBmobUtils.addCollection(collectionList);
                    slidingMenu.showMenu();
                }
                break;
            case R.id.news_add:
                if (!slidingMenu.isSecondaryMenuShowing()) {
                    add_newsChannel.startAnimation(StartAnimation(0f, 225f));
                    slidingMenu.showSecondaryMenu();
                }
                break;
            case R.id.sliding_left_touxiang:
                Intent intent = new Intent(this, MultiImageSelectorActivity.class);

                // 是否显示调用相机拍照
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);

                // 最大图片选择数量
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);

                // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);

                startActivityForResult(intent, Constant.REQUEST_IMAGE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == Constant.REQUEST_IMAGE){
            if(resultCode == RESULT_OK){
                ArrayList<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                String path = mSelectPath.get(0);
                Log.e("path",path);
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                touXiang.setImageBitmap(bitmap);
                menu.setImageBitmap(bitmap);
                File file = new File(path);
                BmobFile bmobFile = new BmobFile(file);
                myBmobUtils.addUserInfo(bmobFile);
            }
        }
    }

    /**
     * 新闻类别的GridView点击事件
     */
    private AdapterView.OnItemClickListener typeGridViewListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView type = (TextView) view.findViewById(R.id.news_label_items_channel);
            if (preTypeSelected != position) {
                type.setBackgroundResource(R.drawable.news_channel_selected_bg);
                type.setTextColor(getResources().getColor(R.color.white));
                tv_preTypeSelected.setBackgroundResource(R.drawable.news_channel_default_bg);
                tv_preTypeSelected.setTextColor(getResources().getColor(R.color.black));
                preTypeSelected = position;
                tv_preTypeSelected = type;
            }
            viewPager.setCurrentItem(position);
            Constant.pos = position;
        }
    };

    /**
     * 设置频道初始化
     *
     * @param position 点击的地方
     */
    private void setChannelTitle(int position) {
        list_title.addAll(XmlParseUtils.list_channelAndNews.get(position).getTitle());
        list_url.addAll(XmlParseUtils.list_channelAndNews.get(position).getUrl());
        for (int i = 0; i < list_title.size(); i++) {
            BaseNews baseNews = new BaseNews(list_title.get(i), list_url.get(i), position, i);
            list.add(baseNews);
        }
        adapter = new MyNewsFragmentAdapter(getSupportFragmentManager(), list);
        viewPager.setAdapter(adapter);
        mIndicator.setViewPager(viewPager);
    }
}
